package com.lzh.ucenter.controller;

import com.google.gson.Gson;
import com.lzh.base.handle.MyException;
import com.lzh.commonutils.JwtUtils;
import com.lzh.ucenter.entity.Member;
import com.lzh.ucenter.service.MemberService;
import com.lzh.ucenter.utils.ConstantWxUtil;
import com.lzh.ucenter.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxController {
    @Autowired
    private MemberService memberService;
    @GetMapping("/login")
    public String genQrConnect() {

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 回调地址
        String redirectUrl = ConstantWxUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            throw new MyException(500, e.getMessage());
        }
        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        return "redirect:" + qrcodeUrl;
    }

    @GetMapping("/callback")
    public String callback(String code, String state) {

        //得到授权临时票据code
//        System.out.println("code = " + code);
//        System.out.println("state = " + state);
        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtil.WX_OPEN_APP_ID,
                ConstantWxUtil.WX_OPEN_APP_SECRET,
                code);

        //请求这个拼接好的地址，得到返回的两个值 access_token openid
        //使用httpClientUtil发送请求
        try {
            String accessInfo = HttpClientUtil.get(accessTokenUrl);
            //System.out.println(accessInfo);
            //从accessInfo中取出两个值access_token和openid
            Gson gson = new Gson();
            //转换为map类型
            HashMap map = gson.fromJson(accessInfo, HashMap.class);
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");

            //把扫描人的微信信息添加到数据库中
            Member user = memberService.getUserByOpenId(openid);
            //数据库没有该用户，保存到数据库
            if (user == null) {
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                //发送请求
                String userInfo = HttpClientUtil.get(userInfoUrl);
                //System.out.println("=================="+userInfo);
                HashMap userMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userMap.get("nickname");
                String headimgurl = (String) userMap.get("headimgurl");
                //将用户添加到数据库
                user = new Member();
                user.setOpenid(openid);
                user.setNickname(nickname);
                user.setAvatar(headimgurl);
                memberService.save(user);
            }

            //使用jwt根据对象生成的token字符串
            String token = JwtUtils.createToken(user.getId(), user.getNickname());
            //返回首页，通过路径传递token字符串
            return "redirect:http://localhost:3000?token="+token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(400,"登录失败");
        }

    }

}
